<?php

include_once '../include/core/image.php';
include_once '../include/core/Excel/excel_reader2.php';
include_once dirname(dirname(__FILE__)) . '/include/common.php';
if ($_SERVER["CONTENT_LENGTH"] / (1024 * 1024) < 8) {
    $core = new core();
    $temp_name = $_FILES['file']['tmp_name'];
    $img_parts = pathinfo($_FILES['file']['name']);
    $ext = strtolower($img_parts['extension']);

    $allowed_ext = array('xls', 'csv');
    if (!in_array($ext, $allowed_ext)) {
        echo '<p class="uperror">Invalid file!</p>';
        exit;
    }
    $temp_file_name = time() . rand(10000, 99999) . session_id() . '.' . $ext;
    $today = getdate();
    $folder_temp = $today["mday"] . "_" . $today["mon"] . "_" . $today["year"];
    if (!is_dir(dirname(dirname(__FILE__)) . "/tmp_photo/" . $folder_temp)) {
        mkdir(dirname(dirname(__FILE__)) . "/tmp_photo/" . $folder_temp);
    }
    $temp_path = dirname(dirname(__FILE__)) . "/tmp_photo/" . $folder_temp . "/" . $temp_file_name;
    try {
        if ($_FILES['file']['size'] > 8 * 1024 * 1024) {
            echo '<p class="uperror">Your file exceeds the size limit. Please make sure it is not larger than 8MB</p>';
            exit;
        }
        if (!move_uploaded_file($temp_name, $temp_path)) {
            echo '<p class="uperror">Upload file is failed.</p>';
            exit;
        }
        $brand = "";
        $name = '';
        $code = "";     
        $des = '';
        $link = '';
        $size = '';
        $color = '';
        $store_price = '';
        $stamp_price = '';
        $product_price = '';
        $old_product_price = '';
        $array_brand = $core->getAllBrand();
               
        $array_brand_id = array();
        $array_brand_id = $array_brand["id"]; //array manufacture_id in table states
        $array_brand_name = array();
        $array_brand_name = $array_brand["name"]; //array lower case "manufacture name" 
        if ($ext == "xls") {
            $data = new Spreadsheet_Excel_Reader($temp_path, true, "UTF-8"); // khoi tao doi tuong doc file excel
            $rowsnum = $data->rowcount($sheet_index = 0); // lay so hang cua sheet
            $colsnum = $data->colcount($sheet_index = 0); // lay so cot cua sheet

            error_reporting(E_ALL ^ E_NOTICE);
            //validate error
            for ($i = 2; $i <= $rowsnum; $i++) {
                for ($j = 1; $j <= $colsnum; $j++) {
                    if ($j == 1) {
                        $brand = trim($data->val($i, $j));
                    } elseif ($j == 2) {
                        $name = trim($data->val($i, $j));
                    } elseif ($j == 3) {
                        $code = trim($data->val($i, $j));
                    } elseif ($j == 4) {
                        $link = trim($data->val($i, $j));
                    } elseif ($j == 5) {
                        $des = trim($data->val($i, $j));
                    } elseif ($j == 6) {
                        $store_price = trim($data->val($i, $j));
                    } elseif ($j == 7) {
                        $stamp_price = trim($data->val($i, $j));
                    } elseif ($j == 8) {
                        $product_price = trim($data->val($i, $j));
                    } elseif ($j == 9) {
                        $old_product_price = trim($data->val($i, $j));
                    } elseif ($j == 10) {
                        $size = trim($data->val($i, $j));
                    }elseif ($j == 11) {
                        $color = trim($data->val($i, $j));
                    } else {
                        break;
                    }
                }

                if ($brand !== "") {
                    $key = array_search(strtolower($brand), $array_brand_name);
                    if ($key === false) {// not exist state
                        echo '<p class="uperror">Line ' . $i . ': Brand does not exist! Please correct it and upload the file again.</p>';
                        exit;
                    }
                } else {
                    echo '<p class="uperror">Line ' . $i . ': Brand name is missing! Please correct it and upload the file again.</p>';
                    exit;
                }
                if ($code === "") {
                    echo '<p class="uperror">Line ' . $i . ': Please enter product code! Please correct it and upload the file again.</p>';
                    exit;
                }
                if ($name === "") {
                    echo '<p class="uperror">Line ' . $i . ': Please enter product name! Please correct it and upload the file again.</p>';
                    exit;
                }
                if ($code === "") {
                    echo '<p class="uperror">Line ' . $i . ': Please enter product code! Please correct it and upload the file again.</p>';
                    exit;
                }
            }
            $img_processor = new OSC_Image ();
            //insert DB
            for ($i = 2; $i <= $rowsnum; $i++) {
                for ($j = 1; $j <= $colsnum; $j++) {
                     if ($j == 1) {
                        $brand = trim($data->val($i, $j));
                    } elseif ($j == 2) {
                        $name = addslashes(trim($data->val($i, $j)));
                    } elseif ($j == 3) {
                        $code = addslashes(trim($data->val($i, $j)));
                    } elseif ($j == 4) {
                        $link = addslashes(trim($data->val($i, $j)));
                    } elseif ($j == 5) {
                        $des = addslashes(trim($data->val($i, $j)));
                    } elseif ($j == 6) {
                        $store_price = trim($data->val($i, $j));
                    } elseif ($j == 7) {
                        $stamp_price = trim($data->val($i, $j));
                    } elseif ($j == 8) {
                        $product_price = intval(trim($data->val($i, $j)))*1000;
                    } elseif ($j == 9) {
                        $old_product_price = intval(trim($data->val($i, $j)))*1000;
                    } elseif ($j == 10) {
                        $size = addslashes(trim($data->val($i, $j)));
                    }elseif ($j == 11) {
                        $color = addslashes(trim($data->val($i, $j)));
                    } else {
                        break;
                    }
                }
                $brand_id = '';
                $key = array_search(strtolower($brand), $array_brand_name);
                $brand_id = $array_brand_id[$key];
                
                //create product image thumb
                $image_name = str_replace("/", ".", $code);
                $source_file_name = $image_name . '.jpg';
                $source_path = dirname(dirname(__FILE__)) . "/photo/" . $source_file_name;
                $path_destince_photo = dirname(dirname(__FILE__)) . "/photo/thumb_photo/200_" . $source_file_name;

                if (is_file($source_path)) {
                    
                    if (is_writable(dirname($path_destince_photo))) {
                        if (copy($source_path, $path_destince_photo)) {
                            chmod(dirname(dirname(__FILE__)) . "/photo/thumb_photo", 0777);
                            chmod($path_destince_photo, 0777);
                            
                            $img_processor->setImage($path_destince_photo)->setJpgQuality(100);
                            $img_processor->resize(200);
                            $img_processor->save();
                        }
                    }
                }
                $exist_product = $core->checkExistProduct($code);

                if (!$exist_product) {
                   // $des= htmlentities($des);
                  
                    $core->db->query("INSERT INTO zen_product (manufacture_id,product_name,
                        product_code,main_photo,description,link_web,product_price,old_product_price,
                        store_price,stamp_price,product_size,product_color) 
                        VALUES ('$brand_id','".$name."','".$code."','".$source_file_name."','".$des."',
                            '".$link."','$product_price','$old_product_price','$store_price','$stamp_price','".$size."','".$color."')");
                }
            }
        }
        echo '  <p class="msg">Product has been added</p>';
        exit;
    } catch (Exception $e) {
        echo '<p class="uperror">' . $e->getMessage() . '</p>';
        exit;
    }
} else {
    echo '<p class="uperror">Your file exceeds the size limit. Please make sure it is not larger than 8MB</p>';
    exit;
}
?> 